package com.survivor.game;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import com.survivor.activity.GameInterface;

import android.content.Context;
import android.opengl.GLU;
import android.opengl.GLSurfaceView.Renderer;
import android.view.MotionEvent;

public class GameRenderer implements Renderer{
	
	GameBackground background;
	GameContent content;
	GameInterface iGame;
	
	GameText gameText;
	
	public GameRenderer(Context context, GameInterface iGame)
	{
		this.iGame = iGame;
		background = new GameBackground(context);
		content = new GameContent(context, iGame);
		content.calculateParams(background.scrOfferX,0);
		gameText = new GameText(context);
	}

	@Override
	public void onDrawFrame(GL10 gl) {
		// TODO Auto-generated method stub
		
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
		gl.glLoadIdentity();
		
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
		
		gl.glEnable(GL10.GL_BLEND);
		gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		
		background.doDraw(gl);
		
		content.doDraw(gl);
		
//		gameText.drawLost(gl);
		gameText.drawPass(gl);
		
		
		gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
		gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
	}

	@Override
	public void onSurfaceChanged(GL10 gl, int width, int height) {
		// TODO Auto-generated method stub
		gl.glViewport(0, 0, width, height);
		gl.glMatrixMode(GL10.GL_PROJECTION);
		gl.glLoadIdentity();
		GLU.gluPerspective(gl, 45f, (float) width / height, .1f, 10f);
	}

	@Override
	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
		// TODO Auto-generated method stub
		loadTextures(gl);
	}
	
	private void loadTextures(GL10 gl)
	{
		gl.glClearColor(0, 0, 0, 1f);
		gl.glEnable(GL10.GL_TEXTURE_2D);
		
		background.loadTexture(gl);
		gl.glLoadIdentity();
		content.loadTextures(gl);
		
		gameText.loadTextures(gl);
		
		gl.glEnable(GL10.GL_CULL_FACE);
		gl.glEnable(GL10.GL_DEPTH_TEST);
		gl.glClearDepthf(1f);
		gl.glDepthFunc(GL10.GL_LEQUAL);
		gl.glShadeModel(GL10.GL_SMOOTH);
	}
	
	public void onTouchEvent(MotionEvent event)
	{
		content.onTouchEvent(event);
	}
}
